package Manage;

import java.io.File;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 



import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
 
public class XMlParser {
	public HashMap<String, HashMap<String, String>> ruleDict = new HashMap<String, HashMap<String, String>>();
	public HashMap<String, HashMap<String, String>> getRuleDict() {
		return ruleDict;
	}

	private static XMlParser m_instance = null;
	private XMlParser() {
		
	}

	public static XMlParser getInstance() {
		if (m_instance == null) {
			m_instance = new XMlParser();
		}
		return m_instance;
	}
	
    public void loadXmlFile(String level) throws Exception {
    	
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        
        String userDir = System.getProperty("user.dir");
		// set the sourcePath
		String sourceFileStr = userDir + "\\..\\" + "Case" + "\\"
				+ "rule_" + level + ".xml";
        File f = new File(sourceFileStr);
        Document doc = builder.parse(f);
        Element root = doc.getDocumentElement();
        //According to root node
        NodeList list = root.getElementsByTagName("model");
        HashMap<String, String> queryDict = new HashMap<String, String>();
    	HashMap<String, String> classMappingDict = new HashMap<String, String>();
    	HashMap<String, String> individualMappingDict = new HashMap<String, String>();
        for (int i = 0; i < list.getLength(); i++) {
            Element elem = (Element) list.item(i);
            String typeName = elem.getAttribute("type");
            
        	NodeList nodes = elem.getChildNodes(); 
        	for(int k=0; k<nodes.getLength(); k++)
        	{
        		Node node = nodes.item(k);
        		if(node.getNodeType() == Node.ELEMENT_NODE)
        		{
        			Element child = (Element)node;
//        			System.out.println(typeName);
//        			System.out.println(child.getNodeName());
//        			System.out.println(child.getTextContent());
        			if(typeName.equals("query"))
                    {
        				queryDict.put(child.getNodeName(), child.getTextContent());
                    }
        			else if(typeName.equals("classMapping"))
        			{
        				classMappingDict.put(child.getNodeName(), child.getTextContent());
        			}
        			else if(typeName.equals("individualMapping"))
        			{
        				individualMappingDict.put(child.getNodeName(), child.getTextContent());
        			}
        			
        		}
        	}
            
        }
        ruleDict.put("query", queryDict);
        ruleDict.put("classMapping", classMappingDict);
        ruleDict.put("individualMapping", individualMappingDict);
        System.out.println("XML parse succeeds!");
    }
 
}